<template>
	<div class="text-sm mb-2 font-bold">上传图片</div>

	<div
		class="w-full h-40 bg-slate-200 rounded-lg border-dashed flex items-center justify-center"
	>
		<el-upload
			:action="uploadUrl"
			:show-file-list="false"
			:on-success="handleSuccess"
			:before-upload="beforeUpload"
			:limit="1"
			drag
			class="w-full"
			v-if="!showProgress && !imageUrl"
		>
			<div class="flex flex-col items-center justify-center">
				<i
					class="iconfont icon-tianjiatupian_huaban"
					style="font-size: 32px"
				></i>
				<div class="text-sm">将文件拖到此处或点击上传</div>
			</div>
		</el-upload>
		<div v-else class="w-full">
			<div
				v-show="showProgress"
				class="text-sm flex justify-center items-center gap-2"
			>
				<div>{{ num }}%</div>
				<div>上传中</div>

				<i
					class="iconfont icon-close"
					style="font-size: 12px"
					@click="handleCancel"
				></i>
			</div>

			<div
				v-show="!showProgress"
				class="relative rounded-lg hover:bg-slate-300 group"
			>
				<div
					class="absolute top-2 right-2 bg-slate-400 text-white w-8 h-8 flex items-center justify-center rounded-md opacity-0 group-hover:opacity-100"
					@click="imageUrl = ''"
				>
					<i class="iconfont icon-shanchu"></i>
				</div>

				<img :src="imageUrl" class="h-40 object-contain mx-auto" />
			</div>
		</div>
	</div>
	<div class="text-zinc-600 text-[12px] mt-2">
		上传最大20 MB的jpg、png、jpeg、webp、gif、heic图像,最小宽度/高度为300像素。
	</div>
</template>

<script setup lang="ts">
import { ElMessage, type UploadProps } from 'element-plus'
import { animation } from '@/utils'
import { baseURL } from '@/utils/request'

// 上传图片的接口
const uploadUrl = baseURL + '/form/upload'

const imageUrl = defineModel<string>()

const showProgress = ref(false)

const num = ref(0)
const start = () => {
	animation(num.value, 99, 3000, (val) => (num.value = val))
}

const handleCancel = () => {
	num.value = 0
	showProgress.value = false
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
	const validTypes = [
		'image/jpeg',
		'image/png',
		'image/jpg',
		'image/webp',
		'image/gif',
		'image/heic',
	]
	if (!validTypes.includes(rawFile.type)) {
		ElMessage.error('图片格式必须为jpg、png、jpeg、webp、gif、heic格式!')
		return false
	} else if (rawFile.size / 1024 / 1024 > 20) {
		ElMessage.error('图片大小不能超过20MB!')
		return false
	}

	//   上传进度
	num.value = 0
	showProgress.value = true
	start()

	return true
}

const handleSuccess: UploadProps['onSuccess'] = (uploadFile) => {
	imageUrl.value = uploadFile.url
	showProgress.value = false
}
</script>

<style scoped lang="scss">
:deep(.el-upload-dragger) {
	width: 100%;
	height: 160px;
	background-color: transparent;
}
</style>
